package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.service.ProductSearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author XB on 2021/11/23 0023.
 * @version 3.0
 */
@Slf4j
@Service
public class ProductSearchServiceImpl implements ProductSearchService {

	@Resource
	RestHighLevelClient restHighLevelClient;

	public boolean getSkuEsmodel(List<SkuEsModel> skuEsModelList) throws IOException {

		BulkRequest bulkRequest = new BulkRequest(EsConstant.PRODUCT_INDEX);
		for (SkuEsModel skuEsModel : skuEsModelList) {
			IndexRequest indexRequest = new IndexRequest();
			indexRequest.id(skuEsModel.getSkuId().toString());
			String s = JSON.toJSONString(skuEsModel);

			indexRequest.source(s, XContentType.JSON);

			bulkRequest.add(indexRequest);
		}

		BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

		// TODO 如果批量错误
		boolean b = bulk.hasFailures();
		List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
			return item.getId();
		}).collect(Collectors.toList());
		log.error("商品上架错误：{}",collect);
		return b;
	}
}
